import Image,ImageDraw, ImageFilter, ImageEnhance
import operator
from pytesser import image_to_string
character_number_mapping = {'Q': '0', 'S': '5', 'O': '0', 'I':'1', 'H' : '4', 'T':'7', 'W' : '4', '?':'7', 'V' : '7', '(' : '6', 'X' : '8'}

multiple_number_mapping = {'F\'': '7', '`if' : '9', '5%' : '9', '`*P':'9', 'Ii':'6', '?r' : '8'}
def get_verify_numbers(image_name):
    im = Image.open(image_name)
    left = 5
    width = 75
    top = 1
    height = 29
    verify_numbers = ""
    for i in range(3):
        verify_number = None
        cropped_im = im.crop((left + width / 3 * i, top, left + width / 3 * (i+1), height));
        remove_noise(cropped_im)
        #cropped_im = enhancer.enhance(1)
        print 'saving cropped file'
        cropped_im.save(str(i+1) + "aaaa.png")
#        characters = image_to_string(cropped_im)
#        for (key, value) in multiple_number_mapping.viewitems():
#                if key in characters:
#                    verify_number = value;
#            
#        if verify_number is None:        
#            for char_index in range(len(characters)):
#                character = characters[char_index]
#                if character.isdigit():
#                    verify_number = character
#                    break;
#                else:
#                    if character_number_mapping.has_key(character):
#                        verify_number  =character_number_mapping[character]
#                        break; 
#                    
#        if verify_number is None:
#            verify_number = '0'
#        verify_numbers = verify_numbers + verify_number
    return verify_numbers

def get_sub_char_images(image_name):
    sub_images = []
    im = Image.open(image_name)
    char_nums = 3
    left = 5
    width = 75
    top = 1
    height = 29
    for i in range(char_nums):
        cropped_im = im.crop((left + width / char_nums * i, top, left + width / char_nums * (i+1), height));
        remove_noise(cropped_im)
        sub_images.append(cropped_im)
    return sub_images

def join_sub_images(sub_images, per_width, height):
    spearator_width = 0
    ocr_image = Image.new("RGBA", (per_width  * len(sub_images) + spearator_width * (len(sub_images) -1 ), height))
    draw = ImageDraw.Draw(ocr_image)
    for i in range(len(sub_images)):
        if i == 0:
            ocr_image.paste(sub_images[i], (i * per_width, 0, (i + 1) * per_width, height))
        else:
            ocr_image.paste(sub_images[i], (i * per_width + spearator_width * i, 0, (i + 1) * per_width + spearator_width * i, height))
    return ocr_image
      
def remove_noise(cropped_im):
    x_size, y_size = cropped_im.size;
    color_count = {}
    color_positions = {};
    pix = cropped_im.load()
    
    for x in range(x_size):
        for y in range(y_size):
            color = pix[x, y] 
            if (x == 0 or y == 0 or y == y_size -1) and color ==1:
                color = 0;
                pix[x, y]=0;
            if color < 10:
                color = 0;
                pix[x, y]=0;
            
            
        
    for x in xrange(1, x_size-1):
        for y in xrange(1, y_size-1):
            color = pix[x, y]
            if color == 0: continue
            N = 0;
            if pix[x-1, y-1] == 0:
                N=N+1
            if pix[x, y-1] == 0:
                N=N+1
            if pix[x+1, y-1] == 0:
                N=N+1
            if pix[x-1, y] == 0:
                N=N+1
            if pix[x+1, y] == 0:
                N=N+1
            if pix[x-1, y+1] == 0:
                N=N+1
            if pix[x, y+1] == 0:
                N=N+1
            if pix[x+1, y+1] == 0:
                N=N+1
            if N > 6:
                pix[x, y]=0
                
#    for x in range(x_size):
#        linecolor = ""
#        for y in range(y_size):
#            color = pix[x, y]
#            if color_positions.has_key(color):
#                color_positions[color].append((x,y))
#            else:
#                color_positions[color] = [(x,y)];    
#            if color_count.has_key(color):
#                color_count[color]  = color_count[color] +1
#            else:
#                color_count[color] = 1
#            linecolor = linecolor +  str(pix[x, y]).ljust(4)
#        print linecolor, '\n'
#        
#    sorted_x = sorted(color_count.iteritems(), key=operator.itemgetter(1))
#    sorted_x.reverse()
#    backgroud = sorted_x[0][0]
#    number_color = sorted_x[1][0]
#    shadow_color =  sorted_x[2][0]
#    color_range = (number_color - shadow_color)/2
#    
#    print 'backgroud: %s, number color: %s , shadow color: %s' % (backgroud, number_color, shadow_color)
#    for (color, amount) in color_count.viewitems():      
#        if (((number_color - color_range)  > color) or (color >  (number_color + color_range))):
#            paste_to_color(color, pix, color_positions, backgroud)
#        else:
#            paste_to_color(color, pix, color_positions, number_color)
#     
#def paste_to_color(color, pix, color_positions, new_color):
#    for (x,y) in color_positions[color]:
#            pix[x, y]= new_color
#        
#            